<?php
declare(strict_types=1);

namespace Service\CommodityService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\GoodsManagerTags;
use App\Model\BbcModel\GoodsBrand;
use App\Model\BbcModel\Goodscommon;
use App\Model\BbcModel\GoodsPriceRule;
use App\Model\BbcModel\GoodsTags;
use App\Model\BbcModel\YunCangSupplier;

/**
 * 定价规则统一配置
 * @author huj
 */
class ChannelCommodityPriceRuleService extends BaseService
{
    /**
     * 自定义规则列表 rule_type=1
     * @param array $param
     */
    public function customRuleList(array $param)
    {
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $model = GoodsPriceRule::where('cid', $param['cid'])->where('rule_type', 1);
        if (isset($param['name']) && !empty($param['name'])) {
            $model = $model->where('name', 'like', "%{$param['name']}%");
        }
        if (isset($param['start_at']) || isset($param['end_at'])) {
            if (isset($param['start_at'])) {
                $startTsp = strtotime($param['start_at']);
                if ($startTsp) {
                    $model = $model->where('md', '>=', $startTsp);
                }
            }
            if (isset($param['end_at'])) {
                $endTsp = strtotime($param['end_at']);
                if ($endTsp) {
                    $model = $model->where('md', '<=', $endTsp);
                }
            }
        }
        if (isset($param['class_id']) && ctype_digit((string)$param['class_id']) && $param['class_id'] > 0) {
            $model = $model->whereRaw("find_in_set({$param['class_id']}, class_ids)");
        }
        if (isset($param['brand_id']) && ctype_digit((string)$param['brand_id']) && $param['brand_id'] > 0) {
            $model = $model->whereRaw("find_in_set({$param['brand_id']}, brand_ids)");
        }
        if (isset($param['tag_id']) && ctype_digit((string)$param['tag_id']) && $param['tag_id'] > 0) {
            $model = $model->whereRaw("find_in_set({$param['tag_id']}, tag_ids)");
        }
        if (isset($param['supply_tag_id']) && ctype_digit((string)$param['supply_tag_id']) && $param['supply_tag_id'] > 0) {
            $model = $model->whereRaw("find_in_set({$param['supply_tag_id']}, supply_tag_ids)");
        }
        if (isset($param['supplier_id']) && ctype_digit((string)$param['supplier_id']) && $param['supplier_id'] > 0) {
            $model = $model->whereRaw("find_in_set({$param['supplier_id']}, supplier_ids)");
        }
        if (isset($param['goods_type']) && ctype_digit((string)$param['goods_type']) && $param['goods_type'] > 0) {
            $model = $model->whereRaw("find_in_set({$param['goods_type']}, goods_types)");
        }
        $fields = [
            'id', 'name', 'goods_num', 'goods_types', 'class_ids', 'brand_ids', 'tag_ids', 'supply_tag_ids',
            'supplier_ids', 'price_type', 'price_store', 'price_recommend_vip', 'price_recommend', 'price_market', 'cd', 'md'
        ];
        $result = $model->select($fields)->orderBy('md', 'desc')->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功', [
                'list'  => [],
                'total' => 0,
            ]);
        }
        $allClass     = GoodsClass::where('cid', $param['cid'])->where('df', 0)->pluck('name', 'id')->toArray();
        $allBrand     = GoodsBrand::where('cid', $param['cid'])->where('df', 0)->pluck('name', 'id')->toArray();
        $allTag       = GoodsManagerTags::where('cid', $param['cid'])->where('df', 0)->pluck('name', 'id')->toArray();
        $allSupplyTag = GoodsTags::where('cid', $param['cid'])->where('type', 0)->pluck('show_name', 'id')->toArray();
        $allSupplier  = YunCangSupplier::where('cid', $param['cid'])->where('supplier_name', '<>', '')->pluck('supplier_name', 'id')->toArray();
        $result->each(function ($item, $key) use ($allClass, $allBrand, $allTag, $allSupplyTag, $allSupplier) {
            $item->goods_types_text = '';
            if (!empty($item->goods_types)) {
                $goodsTypesArr     = explode(',', $item->goods_types);
                $goodsTypesTextArr = [];
                foreach ($goodsTypesArr as $v1) {
                    $str1 = Goodscommon::$is_bonded[$v1] ?? '未定义';
                    array_push($goodsTypesTextArr, $str1);
                }
                if ($goodsTypesTextArr) {
                    $item->goods_types_text = implode(',', $goodsTypesTextArr);
                }
            }
            $item->class_text = '';
            if (!empty($item->class_ids)) {
                $classArr     = explode(',', $item->class_ids);
                $classTextArr = [];
                foreach ($classArr as $v2) {
                    $str2 = $allClass[$v2] ?? '未定义';
                    array_push($classTextArr, $str2);
                }
                if ($classTextArr) {
                    $item->class_text = implode(',', $classTextArr);
                }
            }
            $item->brand_text = '';
            if (!empty($item->brand_ids)) {
                $brandArr     = explode(',', $item->brand_ids);
                $brandTextArr = [];
                foreach ($brandArr as $v3) {
                    $str3 = $allBrand[$v3] ?? '未定义';
                    array_push($brandTextArr, $str3);
                }
                if ($brandTextArr) {
                    $item->brand_text = implode(',', $brandTextArr);
                }
            }
            $item->tag_text = '';
            if (!empty($item->tag_ids)) {
                $tagArr     = explode(',', $item->tag_ids);
                $tagTextArr = [];
                foreach ($tagArr as $v4) {
                    $str4 = $allTag[$v4] ?? '未定义';
                    array_push($tagTextArr, $str4);
                }
                if ($tagTextArr) {
                    $item->tag_text = implode(',', $tagTextArr);
                }
            }
            $item->supply_tag_text = '';
            if (!empty($item->supply_tag_ids)) {
                $supplyTagArr     = explode(',', $item->supply_tag_ids);
                $supplyTagTextArr = [];
                foreach ($supplyTagArr as $v5) {
                    $str5 = $allSupplyTag[$v5] ?? '未定义';
                    array_push($supplyTagTextArr, $str5);
                }
                if ($supplyTagTextArr) {
                    $item->supply_tag_text = implode(',', $supplyTagTextArr);
                }
            }
            $item->supplier_text = '';
            if (!empty($item->supplier_ids)) {
                $supplierArr     = explode(',', $item->supplier_ids);
                $supplierTextArr = [];
                foreach ($supplierArr as $v6) {
                    $str6 = $allSupplier[$v6] ?? '未定义';
                    array_push($supplierTextArr, $str6);
                }
                if ($supplierTextArr) {
                    $item->supplier_text = implode(',', $supplierTextArr);
                }
            }

            $item->price_type_text = GoodsPriceRule::$priceTypeArr[$item->price_type] ?? '';
            $item->cd_text         = date('Y-m-d H:i:s', $item->cd);
            $item->md_text         = date('Y-m-d H:i:s', $item->md);
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', [
            'list'  => $result->items(),
            'total' => $result->total(),
        ]);


    }

    /**
     * 全局规则 rule_type=0
     * @param array $param
     */
    public function globalRuleInfo(array $param)
    {
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $fields = [
            'id', 'price_type', 'price_store', 'price_recommend_vip', 'price_recommend', 'price_market', 'cd'
        ];
        $result = GoodsPriceRule::where('cid', $param['cid'])->where('rule_type', 0)->select($fields)->first();
        if (!$result) {
            return Normal::returnCode(Normal::SUC, '获取成功', []);
        }
        $result->price_type_text = GoodsPriceRule::$priceTypeArr[$result->price_type] ?? '';
        $result->cd_text         = date('Y-m-d H:i:s', $result->cd);
        return Normal::returnCode(Normal::SUC, '获取成功', $result->toArray());
    }
}